/**
 * @funcion : 常用中间件
 * Created by ZY on 2015/11/26
 */

let _ = require('lodash'),
    http = require('../helper/http'),
  errCode = require('../../conf/errorCode'),
  util = require('../helper/util'),
  logger = require('../helper/logger'),
  cst = require('../../conf/const'),
  wrap = require('../helper/wrap');

const INTEGER_REGEXP = /^\d+$/,
  COMMON_COOKIE_OPTIONS = {
    domain: cst.LOGIN_COOKIE_DOMAIN,
    path: cst.LOGIN_COOKIE_PATH,
    maxAge: cst.COMMON_COOKIE_MAX_AGE,
  },
  LOGIN_COOKIE_OPTIONS = _.merge({}, COMMON_COOKIE_OPTIONS, {
    signed: true,
    maxAge: cst.LOGIN_COOKIE_MAX_AGE,
  }),
  LOGOUT_COOKIE_OPTIONS = _.merge({}, LOGIN_COOKIE_OPTIONS, {maxAge: 0});

var tagLogger = new logger.TagLogger('MIDDLEWARE');

exports.authenticate = function(req, res, next) {
  res.set('Cache-Control', 'no-cache,must-revalidate');
  res.set('Expires', 'Thu, 01 Jan 1970 00:00:01 GMT');

  function redirect_to_login() {
    var tps = req.url.match(/\.\w{1,5}/);

    if (tps) {
      tps = tps[0].split('.')[1];
    } else {
      tps = false;
    }
    if (tps === 'json' || tps === 'jsonp') {
      //如果是进行json调用
      return util.sendRes(
        req,
        res,
        util.genCodeObj(errCode.ANY_API, errCode.NOT_LOGIN_ERROR),
      );
    } else {
      res.redirect(`${cst.DOMAIN}/login`);
    }
  }
    console.log(req.signedCookies);
  if (
    req.signedCookies &&
    INTEGER_REGEXP.test(req.signedCookies[cst.LOGIN_SIGNATURE])
  ) {
      console.log('12323123');
    res.cookie(
      cst.LOGIN_SIGNATURE,
      req.signedCookies[cst.LOGIN_SIGNATURE],
      LOGIN_COOKIE_OPTIONS,
    );
    next();
  } else {
      console.log('12312312');
    return redirect_to_login();
  }
};

exports.responseTime = function() {
  return (req, res, next) => {
    req._beginTime = Date.now();
    res.once('finish', () => {
      tagLogger.info(
        '[' + (Date.now() - req._beginTime) + 'ms]' + req.originalUrl,
      );
    });
    next();
  };
};
